import { Component, Input, OnInit, Inject, forwardRef, ViewChild, ElementRef } from '@angular/core';

import { IonSegment } from '@ionic/angular';

import { ComItem } from '../../route/entry/com-item';
import { EventService } from '../../shared/service/event.service';
import { HttpService } from '../../shared/service/http.service';
import { AppGlobalService } from '../../shared/service/app-global.service';

@Component({
    selector: 'app-button-nav',
    templateUrl: './button-nav.component.html',
    styleUrls: ['./button-nav.component.scss']
})
export class ButtonNavComponent implements OnInit {
    @ViewChild("segment", { read: ElementRef }) private segment: ElementRef;
    @ViewChild('segment', null) ionSegment: IonSegment;
    // @ViewChild('subComsSlider') loopSlider: IonSlides;
    receiverTag = 'ButtonNavComponentReceiver';
    // subComs0: ComItem[];
    // subComs1: ComItem[];
    // subComs2: ComItem[];
    // subComs3: ComItem[];
    // subComs4: ComItem[];
    // subComs5: ComItem[];
    // subComs6: ComItem[];
    // subComs7: ComItem[];
    subComs8: ComItem[];
    // subComs9: ComItem[];
    // subComs10: ComItem[];

    @Input() tagData: any;
    aWidth: string;
    isSelected: boolean;
    currentClickObj: any;
    currentCLickIndexTab: any;
    isRootURL: any; // 用于检查URL是否有变化
    selectedSegment = 0;
    // slideOptsHome = {
    //     autoplay: false,
    //     autoHeight: true,
    //     effect: 'flip',
    //     speed: 400
    // };
    constructor(
        private eventService: EventService,
        private httpService: HttpService,
        private appGlobalService: AppGlobalService
    ) {
        if (this.eventService.eventEmit.listenerCount(this.receiverTag) > 0) {
            this.eventService.eventEmit.removeListener(this.receiverTag);
        }
        this.eventService.eventEmit.on(this.receiverTag, res => {
            if (localStorage.getItem(this.receiverTag + 'Tag')) {
                localStorage.removeItem(this.receiverTag + 'Tag');
                this.subComs8 = res.coms;
            }
        });
    }

    // async onSlideChanged(slider: IonSlides) {
    //     const slideIndex = await this.loopSlider.getActiveIndex();
    //     this.selectedSegment = +slideIndex;
    //     await this.showIndicator();
    //     // document.getElementById('segmentIndicator' + this.selectedSegment).style.display = "block";
    //     this.loopSlider.updateAutoHeight();
    // }

    async segmentChanged(e: any) {
        const index = e.detail.value;
        const segmentButton = this.segment.nativeElement.children[index];
        segmentButton.scrollIntoView({
            behavior: 'smooth',
            inline: 'center',
            block: 'nearest'
        });

        // this.loopSlider.slideTo(index);
        await this.showIndicator();
        if (this.tagData.data) {
            this.httpService.post('application/part',
                {
                    viewId: this.tagData.data[index].partLink.target,
                    sessionId: localStorage.getItem("sessionId"),
                    params: this.tagData.data[index].partLink.params
                }, (res: any) => {
                    if (res) {
                        const tmpData = JSON.parse(res.script);
                        // 发送事件
                        const eventEmitObj = { data: tmpData, receiverTag: this.receiverTag };
                        localStorage.setItem('generatedComItemWithBufferTag', JSON.stringify(eventEmitObj));
                        this.eventService.eventEmit.emit('generatedComItemWithBuffer', '');
                        // this.tabService.getPageDataWithBuffer(tmpData, callData => {
                        //     this.subComs8 = callData.coms;
                        // });
                    }
                });
        }
        // document.getElementById('segmentIndicator' + index).style.display = "block";
        // this.loopSlider.updateAutoHeight();
    }

    showIndicator() {
        const len = this.tagData.data.length;
        // for (let i = 0; i < len; i++) {
        //     document.getElementById('segmentIndicator' + i).style.display = "none";
        // }

        // bug: #574 切换tab页后应从当前tab的第一条信息开始展示
        const contents = document.querySelectorAll('ion-content');
        const ele = document.querySelector('ion-content #scrollContent');
        let target = null;
        contents.forEach(item => {
            if (this.isChildOf(ele, item)) {
                target = item;
            }
        });
        target.getScrollElement().then(e => {
            if (e.scrollTop >= document.getElementById('scrollContent').offsetTop) {
                target.scrollToPoint(0, document.getElementById('scrollContent').offsetTop + 44);
            }
        });
    }
    /**
     * 判断是否子节点
     * @param child 子节点
     * @param parent 父节点
     */
    isChildOf(child, parent) {
        let parentNode;
        if (child && parent) {
            parentNode = child.parentNode;
            while (parentNode) {
                if (parent === parentNode) {
                    return true;
                }
                parentNode = parentNode.parentNode;
            }
        }
        return false;
    }
    async ngOnInit() {
        const that = this;
        this.aWidth = 100 / this.tagData.data.length + '%';
        const cDataObj = this.tagData.currentData;
        this.selectedSegment = +this.tagData.currentTab;
        if (cDataObj && cDataObj !== undefined) {
            const tags = cDataObj.tags;
            if (tags !== undefined && tags.length > 0) {
                that.httpService.post('application/part',
                    {
                        viewId: this.tagData.data[0].partLink.target,
                        sessionId: localStorage.getItem("sessionId"),
                        params: this.tagData.data[0].partLink.params
                    }, (res: any) => {
                        if (res) {
                            const tmpData = JSON.parse(res.script);
                            // #task-view-916
                            if (this.tagData.refresh) {
                                tmpData.isPullToRefresh = this.tagData.refresh;
                            }
                            // tmpData.isPullToRefresh = true;
                            // 发送事件
                            const eventEmitObj = { data: tmpData, receiverTag: this.receiverTag };
                            localStorage.setItem('generatedComItemWithBufferTag', JSON.stringify(eventEmitObj));
                            this.eventService.eventEmit.emit('generatedComItemWithBuffer', '');
                            // this.tabService.getPageDataWithBuffer(tmpData, callData => {
                            //     that.subComs8 = callData.coms;
                            // });
                        }
                    });
            }
        }
    }

    dismiss() {
        this.appGlobalService.goBack();
    }

    get(obj) {
        const params = {
            pageId: obj.target,
            params: obj.params,
            sessionId: localStorage.getItem('sessionId')
        };
        this.appGlobalService.goToForward(params);
    }
}
